/**
 * @file
 * @auth jinguangguo
 * @date 2016/12/29
 */

import Vue from 'vue';
import tpl from './tpl.html';
import Loading from '../../../../../grsc-base/component/Loading.vue';
import PersonInfo from '../component/PersonInfo.vue';
import RecommendSell from '../component/RecommendSell.vue';
import service from '../service';
import CnyChangeInput from '../../components/cnyChangeInput.vue';
import commonService from '../../../../common/commonService';
import setPhone from '../../../../component/setPhone.vue'
import mathtool from '../../../../../grsc-base/util/mathtool';
import filter from '../../../../../grsc-base/util/filter';
import format from '../../../../common/format';
import Clipboard from 'clipboard';

export default Vue.extend({
    name: 'index',
    template: tpl,
    components: {
        Loading,
        PersonInfo,
        RecommendSell,
        CnyChangeInput,
        setPhone
    },
    data(){
        return {
            advertId: +this.$route.params.adId,
            isLoading: true,
            level: '',
            isRequesting: false,
            type:'actSell',
            isSettingPhone: false,
            form: {
                payType: 'ALIPAY',
                remark: '',
                amount: '',
                total: ''
            },
            orderBaseInfo: {
                phone: '',
                tradePrice: '',// 当前价格
                country: '',  // 国家
                assetcode: '',  // 币种code
                currency: '',  // 国家
                maxAmount: '',  // 最大值
                minAmount: '',  // 最小值
                nickName: '',  // 昵称
                payType: [],  // 支付类型
                remark: '',  // 备注
                isFaildTrade: false, // 购买失败
                isHadBuyTrad: false  // 已经被买
            },
            // CNY ATC BTC USC转换错误提示
            totalError: ' ',
            amountError: ' ',
            precision: 4,

            isShare: false,
            shareUrl: window.location.href,
            clipboard: null
        }
    },
    created() {
        this.isLoading = true;
        this.getBaseInfo();

        this.realAuthDetection();
    },
    watch:{
        
    },
    mounted(){
        // this.toCopy()
    },
    methods: {
        //检验用户是否实名认证
        realAuthDetection () {
            commonService.basic().done((basicRep) => {
                // console.log(basicRep,'实名')
                if (basicRep.code === window.CODE.SUCCESS) {
                    let user = basicRep.data;
                    this.level = user.authLevel;
                }
            });
        },
        // 获取基本信息
        getBaseInfo(){
            this.isLoading = true;
            service.sellDetailQuery({
                advertId: this.advertId
            }).done((rep) => {
                let data;
                if (rep.code === window.CODE.SUCCESS) {
                    // console.log(rep.data,'基本信息');
                    this.isLoading = false;
                    data = rep.data;
                    this.orderBaseInfo = data;

                    // console.log(`原始最小值${data.minMoney}=====原始最大值${data.maxMoney}`)

                    this.orderBaseInfo.minMoney = filter.floorFix(data.minMoney,2);
                    this.orderBaseInfo.maxMoney = filter.floorFix(data.maxMoney,2);
                    this.orderBaseInfo.tradePrice = filter.floorFix(data.tradePrice,2);

                    // console.log(`计算最小值${this.orderBaseInfo.minMoney}=====计算最大值${this.orderBaseInfo.maxMoney}`)

                    this.form.payType = this.orderBaseInfo.payType[0];  // 默认的支付方式
                    // 设置小数位数
                    this.precision = this.orderBaseInfo.assetcode === 'BTC' ? 8 : 4;
                }
            }).always((req) => {
                // console.log('基本信息获取失败',req)
                this.getAdState(req.code)
                
            });
        },
        changePayType(){
            console.log(this.form.payType)
        },
        submit(){
            if(!this.form.amount){
                // this.totalError = '請輸入想買入的金額';
                this.amountError = '請輸入想買入的'+this.orderBaseInfo.assetcode+'數量';
                return
            }
            if(this.amountError !==' ' || this.totalError!==' '){
                return;
            }
            this.isRequesting = true;
            this.createAdSell();
        },
        setPhoneCbFn(){
            // console.log('设置手机成功回调函数')
            this.createAdSell()
        },
        setPhoneHide(){
            this.isRequesting = false;
            this.isSettingPhone = false;
        },
        createAdSell(){
            service.createAdOrder({
                advertId: this.advertId, // url
                number: this.form.amount,   // ACT BCT USC
                money: this.form.total,  //CNY
                remark: this.form.remark,
                payType: this.form.payType
            }).done((rep) => {
                let data;
                if (rep.code === window.CODE.SUCCESS) {
                    let c2cTransOrderNum = rep.data.c2cTransOrderNum;
                    window.success(rep.msg);
                    setTimeout(()=>{
                        // this.$router.push({name: 'adDetailSellRes', params: {c2cTransOrderNum: c2cTransOrderNum, totalMoney: this.form.total}})
                        window.location.href = './c2c.html#/ad/detail/sell-res/'+ c2cTransOrderNum +'?totalMoney=' + window.encodeURIComponent(filter.floorFix(this.form.total,2));
                    },2000);
                    return;
                }else if(rep.code === '115107'){
                    // 用户未设置手机号
                    this.isSettingPhone = true;
                    return;
                }else if(rep.code === '105102'){
                    // 用户未登陆
                    setTimeout(()=>{
                        window.location.href = './login.html?from=' + window.encodeURIComponent(window.location.href);
                    },2000);
                }
                window.error(rep.msg);
                this.isRequesting = false;
            }).always((req) => {
                this.getAdState(req.code)
                this.isRequesting = false;
                // this.isLoading = false;
            });
        },
        // rmb输入
        changeTotal(){
            this.clearError()
            if ($.isNumeric(this.form.total) === false || $.isNumeric(this.orderBaseInfo.tradePrice) === false) {
                return '';
            }
            let amount = filter.floorFixPrice(mathtool.division(this.form.total, this.orderBaseInfo.tradePrice),this.precision);
            this.form.amount = format.formatZeroSuffix(amount,this.precision);

            if(+this.form.total> +this.orderBaseInfo.maxMoney){
               this.totalError =  '不能超出交易的CNY上限額';
               return;
            }
            if(+this.form.total< +this.orderBaseInfo.minMoney){
               this.totalError =  '不能低于交易的CNY下限額';
               return;
            }

        },

        changeAmount(){
            this.clearError()
            if ($.isNumeric(this.form.amount) === false || $.isNumeric(this.orderBaseInfo.tradePrice) === false) {
                return '';
            }

            let total = filter.floorFix(mathtool.multiplication(this.form.amount, this.orderBaseInfo.tradePrice), 2);

            this.form.total =  format.formatZeroSuffix(total, 2);
            
            if(+this.form.total> +this.orderBaseInfo.maxMoney){
               // this.totalError =  '不能超出交易限額'
               this.amountError =  '不能超出交易的CNY上限額'
               return;
            }
            if(+this.form.total< +this.orderBaseInfo.minMoney){
               // this.totalError =  '不能低于交易最小值'
               this.amountError =  '不能低于交易的CNY下限額'
               return;
            }
        },
        clearError(cbfn){
            this.amountError = ' '
            this.totalError =  ' '
        },
        toShare(){
            this.toCopy();
            this.isShare = true;
        },
        shareClose(){
            this.isShare = false;
        },

        // 已经购买  删除
        getAdState(status){
            // console.log(status);
            if(status === '115100'){
                // 已经买走
                this.orderBaseInfo.isHadBuyTrad = true;
                return 
            }
            if(status === '115101'){
                // 已经删除
                this.orderBaseInfo.isFaildTrade = true;
                return 
            }
        },
        faildTradeClose(){
            this.orderBaseInfo.isFaildTrade = false;
            window.location.href = './c2c.html';
        },
        hadBuyClose(){
            this.orderBaseInfo.isHadBuyTrad = false;
            window.location.href = './c2c.html';
        },
        // 去kyc认证页面
        toKYCPage(){
            window.location.href = './account.html#/certification';
        },
        toCopy(){
            let that = this;
            this.clipboard = new Clipboard('.btn', {
                // 点击copy按钮，直接通过text直接返回复印的内容
                text: function() {
                    return that.shareUrl;
                }
            });

            //复制成功执行的回调，可选
            this.clipboard.on('success', function(e) {
                window.success('複製成功')
                console.log(e);
            });

            //复制失败执行的回调，可选
            this.clipboard.on('error', function(e) {
                console.log(e);
                window.error('複製失敗')
            });
            this.clipboard = null;
        }
    }
});
